#!/bin/bash

# 临时启用IPv4反向路径过滤
echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter
echo 1 > /proc/sys/net/ipv4/conf/default/rp_filter

# 注释掉系统默认配置文件中的冲突设置
for conf_file in /lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do
    if [ -f "$conf_file" ]; then
        sed -i 's/^\(net\.ipv4\.conf\.\(all\|default\)\.rp_filter[[:space:]]*=[[:space:]]*\)2/#\1 2/' "$conf_file"
    fi
done

# 永久启用IPv4反向路径过滤
if grep -q "^net.ipv4.conf.all.rp_filter" /etc/sysctl.conf; then
    sed -i 's/^net.ipv4.conf.all.rp_filter.*/net.ipv4.conf.all.rp_filter=1/' /etc/sysctl.conf
else
    echo "net.ipv4.conf.all.rp_filter=1" >> /etc/sysctl.conf
fi

if grep -q "^net.ipv4.conf.default.rp_filter" /etc/sysctl.conf; then
    sed -i 's/^net.ipv4.conf.default.rp_filter.*/net.ipv4.conf.default.rp_filter=1/' /etc/sysctl.conf
else
    echo "net.ipv4.conf.default.rp_filter=1" >> /etc/sysctl.conf
fi

# 应用配置
sysctl -p >/dev/null 2>&1

echo "反向路径过滤配置完成"
